<template>
  <div class="diary-overview">
    <h2>手账总览</h2>
    <div v-if="diaries.length > 0">
      <div class="diary-container">
        <div v-for="diary in diaries" :key="diary.diaryId" class="diary-item">
          <div class="diary-item-content">
            <router-link :to="{ name: 'DiaryDetail', params: { diaryId: diary.diaryId } }">
              <img :src="require('../../../assets/b1.jpg')" alt="手账预览" class="diary-imgs">
              <h3>{{ diary.diaryName}}</h3>
            </router-link>
            <button @click="deleteDiary(diary)" class="btn delete-btn">删除</button>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="empty-display">
      <p>选择一个地点来新增手账
        <button @click="gotoLocationPage">跳转中~</button></p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  name: 'JournalOverview', 
  data() {
    return {
      diaries: [] 
    };
  },
  created() {
    this.fetchDiaries(); 
  },
  
  methods: {
    fetchDiaries() {
      const token =  localStorage.getItem('userToken');
      axios.get('/api/diarys/mydiarys', 
      { headers: { 'Authorization': token } })
        .then(response => {
          this.diaries = response.data.data; // Update diaries with fetched data
        })
        .catch(error => {
          console.error('Error fetching diaries:', error);
        });
    },
    goToAddDiary() {
      this.$router.push({ name: 'AddDiary' }); // Changed to reflect actual routing
    },
    deleteDiary(diary) {
      const diaryId = diary.diaryId;
      const token = localStorage.getItem('userToken');
      const index = this.diaries.findIndex(item => item.diaryId === diaryId);
      if (index !== -1) {
        axios.delete(`/api/diarys/delete`, {
          headers: { 'Authorization': token },
          params: { diaryId: diaryId }
        })
        .then(() => {
          this.diaries.splice(index, 1);
          console.log('Diary deleted');
        })
   }
},
    gotoLocationPage() {
    this.$router.push({ name: 'location' });
  }
  }
};
</script>
<style>
 @import "@/assets/css/overview.css";
</style>
